from rest_framework import serializers
from apps.users.models import User
import re
from django_redis import get_redis_connection

# 继承ModelSerializer 是因为有create()和update()方法
class RegisterCreateSerializer(serializers.ModelSerializer):

    password2 = serializers.CharField(label='校验密码', allow_null=False, allow_blank=False, write_only=True)
    sms_code = serializers.CharField(label='短信验证码', max_length=6, min_length=6, allow_null=False, allow_blank=False,                               write_only=True)
    allow = serializers.CharField(label='是否同意协议', allow_null=False, allow_blank=False, write_only=True)

    class Mate:
        model = User
        extar_kwargs = {
            'id':{'read_only',True},
            'username':{
                'min_length':5,
                'max_length':20,
                'error_massages':{
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }
    # 单个字段校验
        # 校验手机号和是否同意协议
    def mobile(self,attrs):
        # 校验手机号
        if re.match(r'1[345789]\d{9}',attrs):
            raise serializers.ValidationError('手机号格式不对')
        return attrs

    def validation(self,attrs):
        """
        验证用户是否同意
        :param attrs:参数
        :return: attrs
        """
        if attrs != True:
            raise serializers.ValidationError('您未同意协议')
        return attrs

    # 多个字段校验
        #密码和确认密码
    def password(self,attrs):
        password1 = attrs['password']
        password2 = attrs['password2']
        if password1 != password2:
            raise serializers.ValidationError('两次密码输入不一致')
        return attrs

        # 校验短信验证码
    def send_sms_code(self,attrs):
        # 获取用户提交的短信验证码
        code = attrs['sms_code']
        # 连接redis
        redis = get_redis_connection('code')
        # 获取手机号/通过手机号获取redis中的短信验证码
        mobile = attrs['mobile']
        redis_code = redis.get('sms_%s'%mobile)
        if redis_code is None:
            raise serializers.ValidationError('验证码已经过期')

        if redis_code != code:
            raise serializers.ValidationError('验证码不一致')

        return attrs

    # 我们在序列化器中添加啦三个字段不用添加到数据库中,所以我们可以重写cerate方法
    def create(self,validated_data):

        del validated_data['password2']
        del validated_data['allow']
        del validated_data['sms_code']

        # 重新入库
        user = User.objects.create(validated_data)
        # user = super().create(validated_data)

        # 给入库的密码进行加密
        user.set_password()

        return user